package edu.sysu.demo.petstore.dog.data.converter;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import edu.sysu.demo.petstore.dog.data.entity.Key.KeyType;
import java.util.Map;
import java.util.stream.Stream;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class KeyTypeConverter implements AttributeConverter<KeyType, Integer> {

  private static final Map<Integer, KeyType> MAPPING;

  @Override
  public Integer convertToDatabaseColumn(KeyType attribute) {
    return attribute.getValue();
  }

  @Override
  public KeyType convertToEntityAttribute(Integer dbData) {
    return MAPPING.get(dbData);
  }

  static {
    ImmutableMap.Builder<Integer, KeyType> builder = new Builder<>();
    Stream.of(KeyType.values())
        .forEach(keyType -> builder.put(keyType.getValue(), keyType));
    MAPPING = builder.build();
  }
}
